namespace BM.Tools.WebControls.MForm.Navigation.XPath
{
    using System;

    /// <summary>
    /// A definition single location step in xpath.
    /// </summary>
    public class SingleLocationStep : LocationStep
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="SingleLocationStep"/> class. 
        /// </summary>
        /// <param name="nodeTest">
        /// The node test.
        /// </param>
        /// <param name="predicate">
        /// The predicate.
        /// </param>
        public SingleLocationStep(NodeTest nodeTest, Predicate predicate)
        {
            NodeTest = nodeTest;
            Predicate = predicate;
        }

        /// <summary>
        /// Gets or sets NodeTest.
        /// </summary>
        /// <value>
        /// The node test.
        /// </value>
        public NodeTest NodeTest
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets Predicate.
        /// </summary>
        /// <value>
        /// The predicate.
        /// </value>
        public Predicate Predicate
        {
            get;
            set;
        }

        /// <summary>
        /// Creates the location step out of its string definition
        /// </summary>
        /// <param name="locationStepText">
        /// The locationStepText.
        /// </param>
        /// <returns>
        /// the <see cref="SingleLocationStep" /> object
        /// </returns>
        public static new SingleLocationStep Create(string locationStepText)
        {
            string predicates = null;
            string nodeTest = locationStepText;
            int bracketOpenIndex = locationStepText.IndexOf("[", StringComparison.Ordinal);
            int bracketCloseIndex = locationStepText.IndexOf("]", StringComparison.Ordinal);
            if (bracketOpenIndex != -1 && bracketCloseIndex != -1)
            {
                predicates = locationStepText.Substring(bracketOpenIndex + 1, bracketCloseIndex - bracketOpenIndex - 1);
                nodeTest = locationStepText.Substring(0, bracketOpenIndex);
            }

            return new SingleLocationStep(NodeTest.Create(nodeTest), Predicate.Create(predicates));
        }
    }
}